package component.util;

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;

public class BaseMotionAdapter extends MouseAdapter {

	private Component component = null;
	private JPanel panel;

	public void setComponent(Component component) {
		this.component = component;
	}

	public void setPanel(JPanel panel) {
		this.panel = panel;
	}

	public BaseMotionAdapter(Component remoteComponent, JPanel panel) {
		this.component = remoteComponent;
		component.addMouseMotionListener(this);
		this.panel = panel;
	}

	public void mouseDragged(MouseEvent e) {
		this.updateLocation(e);
	}

	private void updateLocation(MouseEvent e) {
		component.setLocation(e.getX() + component.getX()
				- component.getWidth() / 2, e.getY() + component.getY()
				- component.getHeight() / 2);
		if (component.getLocation().x <= 0) {
			component.setLocation(0, component.getLocation().y);
		}
		if (component.getLocation().y <= 0) {
			component.setLocation(component.getLocation().x, 0);
		}
		if (component.getLocation().x + component.getWidth() >= panel
				.getWidth()) {
			component.setLocation(panel.getWidth() - component.getWidth(),
					component.getLocation().y);
		}
		if (component.getLocation().y + component.getHeight() >= panel
				.getHeight()) {
			component.setLocation(component.getLocation().x, panel.getHeight()
					- component.getHeight());
		}
	}

	public void redispatchEvent(final MouseEvent e) {
		final Component origin = e.getComponent();
		e.setSource(origin.getParent());
		e.translatePoint(origin.getX(), origin.getY());
		origin.getParent().dispatchEvent(e);
	}
}
